<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>教师管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">新增教师</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
          <el-button @click="handleExportTeachers">导出教师</el-button>
          <el-button @click="previewTeacherTemplate">下载模板</el-button>
          <el-button @click="importTeachers">导入教师</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索条件 -->
    <el-form :model="searchForm" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="工号">
            <el-input v-model="searchForm.teacherId" placeholder="请输入工号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 教师列表 -->
    <el-table :data="teacherList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="teacherNo" label="工号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="collegeName" label="学院" width="150" />
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="employmentDate" label="入职日期" width="120" />
      <!-- 移除了创建时间列 -->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="工号" prop="teacherNo">
          <el-input v-model="form.teacherNo" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="学院" prop="collegeId">
          <el-select v-model="form.collegeId" placeholder="请选择学院" style="width: 100%">
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="form.title" placeholder="请选择职称" style="width: 100%">
            <el-option label="助教" value="助教" />
            <el-option label="讲师" value="讲师" />
            <el-option label="副教授" value="副教授" />
            <el-option label="教授" value="教授" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期" prop="employmentDate">
          <el-date-picker
            v-model="form.employmentDate"
            type="date"
            placeholder="选择入职日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入教师数据" width="500px">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="http://localhost:8080/api/teachers/import"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload" :loading="uploadLoading">
          上传到服务器
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件 (.xlsx)，下载模板请点上方"下载模板"按钮
          </div>
        </template>
      </el-upload>
    </el-dialog>
    
    <!-- 教师模板预览对话框 -->
    <el-dialog v-model="templatePreviewVisible" title="教师导入模板预览" width="800px">
      <el-table :data="templatePreviewData" border style="width: 100%">
        <el-table-column prop="teacherNo" label="工号" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="collegeName" label="学院" width="150" />
        <el-table-column prop="title" label="职称" width="150" />
        <el-table-column prop="employmentDate" label="入职日期" width="150" />
      </el-table>
      <div class="template-preview-footer">
        <p>以上为教师导入模板的结构示例，请按照此格式填写数据</p>
        <el-button type="primary" @click="downloadTeacherTemplate">下载模板文件</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  teacherId: '',
  name: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 教师列表
const teacherList = ref([])

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 导入相关
const importDialogVisible = ref(false)
const uploadRef = ref()
const uploadLoading = ref(false)
const selectedFile = ref(null)

// 模板预览相关
const templatePreviewVisible = ref(false)
const templatePreviewData = ref([
  {
    teacherNo: 'T001',
    name: '李四',
    collegeName: '软件学院',
    title: '教授',
    employmentDate: '2020-09-01'
  }
])

// 下拉选项数据
const collegeOptions = ref([])

// 表单数据
const form = reactive({
  id: '',
  teacherNo: '',
  name: '',
  collegeId: '',  // 添加这行来包含学院ID字段
  title: '',
  employmentDate: ''
})

// 表单验证规则
const rules = {
  teacherNo: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  title: [{ required: true, message: '请选择职称', trigger: 'change' }],
  employmentDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }]
}

const formRef = ref()

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 添加一个专门用于格式化日期字段的函数（不包含时间）
const formatDateOnly = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
}

// 获取教师列表
const fetchTeachers = async () => {
  loading.value = true
  try {
    // 添加分页参数和搜索参数
    const params = new URLSearchParams();
    params.append('page', pagination.currentPage - 1); // 后端分页从0开始
    params.append('size', pagination.pageSize);
    
    // 添加搜索参数
    if (searchForm.teacherId) {
      params.append('teacherNo', searchForm.teacherId);
    }
    if (searchForm.name) {
      params.append('name', searchForm.name);
    }
    
    const response = await axios.get(`http://localhost:8080/api/teachers?${params.toString()}`);
    
    // 添加调试信息
    console.log('教师列表响应数据:', response.data);
    
    teacherList.value = response.data.content.map(teacher => ({
      ...teacher,
      // 移除了createTime字段的处理
      employmentDate: formatDateOnly(teacher.employmentDate)  // 格式化入职日期
    }))
    
    // 添加调试信息
    console.log('处理后的教师列表:', teacherList.value);
    
    pagination.total = response.data.totalElements
  } catch (error) {
    console.error('获取教师列表失败:', error)
    ElMessage.error('获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 获取学院列表
const fetchColleges = async () => {
  try {
    // 添加分页参数，获取所有学院
    const params = new URLSearchParams();
    params.append('page', 0); // 获取第一页
    params.append('size', 1000); // 设置一个较大的页面大小以获取所有学院
    
    const response = await axios.get(`http://localhost:8080/api/colleges?${params.toString()}`);
    // 处理分页响应数据
    collegeOptions.value = response.data.content || response.data;
  } catch (error) {
    console.error('获取学院列表失败:', error);
    ElMessage.error('获取学院列表失败');
  }
}

// 搜索
const handleSearch = async () => {
  console.log('搜索:', searchForm)
  // 重置到第一页
  pagination.currentPage = 1
  await fetchTeachers()
}

// 重置
const handleReset = () => {
  searchForm.teacherId = ''
  searchForm.name = ''
  // 重置到第一页
  pagination.currentPage = 1
  fetchTeachers()
}

// 刷新
const handleRefresh = () => {
  fetchTeachers()
}

// 预览教师模板
const previewTeacherTemplate = () => {
  templatePreviewVisible.value = true;
}

// 下载教师模板
const downloadTeacherTemplate = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/teachers/template', {
      responseType: 'blob'
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '教师导入模板.xlsx');
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('模板下载成功');
    templatePreviewVisible.value = false;
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
}

// 导入教师
const importTeachers = () => {
  importDialogVisible.value = true;
}

// 处理文件选择
const handleFileChange = (file) => {
  selectedFile.value = file.raw;
}

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }
  
  uploadLoading.value = true;
  
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  
  try {
    const response = await axios.post('http://localhost:8080/api/teachers/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    ElMessage.success(response.data);
    importDialogVisible.value = false;
    fetchTeachers(); // 刷新教师列表
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + (error.response?.data || error.message));
  } finally {
    uploadLoading.value = false;
  }
}

// 上传成功处理
const handleUploadSuccess = (response, file, fileList) => {
  uploadLoading.value = false;
  ElMessage.success('导入成功');
  importDialogVisible.value = false;
  fetchTeachers(); // 刷新教师列表
}

// 上传失败处理
const handleUploadError = (error, file, fileList) => {
  uploadLoading.value = false;
  ElMessage.error('导入失败: ' + error);
}

// 新增
const handleAdd = async () => {
  dialogTitle.value = '新增教师'
  isEdit.value = false
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
  // 加载下拉选项数据
  await fetchColleges()
}

// 编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑教师'
  isEdit.value = true
  // 填充表单数据
  form.id = row.id
  form.userId = row.userId  // 添加这行来正确填充userId
  form.teacherNo = row.teacherNo
  form.name = row.name
  form.collegeId = row.collegeId
  form.title = row.title
  form.employmentDate = row.employmentDate
  dialogVisible.value = true
  // 加载下拉选项数据
  await fetchColleges()
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教师 ${row.name} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除
    await axios.delete(`http://localhost:8080/api/teachers/${row.id}`)
    ElMessage.success('删除成功')
    // 重置到第一页并重新加载数据
    pagination.currentPage = 1
    fetchTeachers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除教师失败:', error)
      ElMessage.error('删除教师失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化入职日期
        let employmentDate = form.employmentDate;
        if (employmentDate instanceof Date) {
          employmentDate = employmentDate.toISOString().split('T')[0]; // 转换为 YYYY-MM-DD 格式
        }
        
        if (isEdit.value) {
          // 编辑操作 - 直接更新教师信息
          const teacherData = {
            userId: form.userId, // 保留原有的userId
            teacherNo: form.teacherNo,
            collegeId: form.collegeId,  // 添加这行来正确提交学院ID
            title: form.title,
            employmentDate: employmentDate
          };
          
          // 同时更新用户表中的姓名信息
          const userData = {
            realName: form.name
          };
          
          // 并行更新教师和用户信息
          await Promise.all([
            axios.put(`http://localhost:8080/api/teachers/${form.id}`, teacherData),
            axios.put(`http://localhost:8080/api/users/${form.userId}`, userData)
          ]);
          
          ElMessage.success('编辑成功')
        } else {
          // 新增操作 - 先创建用户，再创建教师
          // 1. 创建用户
          const userData = {
            username: form.teacherNo, // 使用工号作为用户名
            realName: form.name,
            gender: '男', // 默认值改为数据库允许的值
            role: 'teacher',
            status: 'active',
            password: '$2a$10$7JB720yubVSOfvK5j6s0oOjGHOOzn2oLs1yLowJO0aPjJ9zJ5jEAu' // 默认密码123456的哈希值
          };
          
          const userResponse = await axios.post('http://localhost:8080/api/users', userData);
          const userId = userResponse.data.id;
          
          // 2. 创建教师记录
          const teacherData = {
            userId: userId,
            teacherNo: form.teacherNo,
            collegeId: form.collegeId,  // 添加这行来正确提交学院ID
            title: form.title,
            employmentDate: employmentDate
          };
          
          await axios.post('http://localhost:8080/api/teachers', teacherData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        // 重置到第一页并重新加载数据
        pagination.currentPage = 1
        fetchTeachers()
      } catch (error) {
        console.error('操作失败:', error)
        console.error('Response data:', error.response?.data);
        ElMessage.error('操作失败: ' + (error.response?.data?.message || error.response?.data || error.message))
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 重置到第一页
  pagination.currentPage = 1
  fetchTeachers()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTeachers()
}

// 导出教师列表
const handleExportTeachers = async () => {
  try {
    // 发起导出请求
    const response = await axios({
      method: 'get',
      url: 'http://localhost:8080/api/teachers/export',
      responseType: 'blob' // 重要：设置响应类型为blob
    });
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '教师列表.xlsx';
    link.click();
    
    // 清理URL对象
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + (error.response?.data?.message || error.message));
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchTeachers()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.template-preview-footer {
  margin-top: 20px;
  text-align: center;
}

.template-preview-footer p {
  margin-bottom: 15px;
  color: #666;
}
</style>